package com.hgb.mall.admin.services.impl;

import com.github.pagehelper.PageHelper;
import com.hgb.mall.admin.dao.OmsOrderDao;
import com.hgb.mall.admin.dao.OmsOrderOperateHistoryDao;
import com.hgb.mall.admin.dto.*;
import com.hgb.mall.admin.services.OmsOrderService;
import com.hgb.mall.admin.services.UmsAdminService;
import com.hgb.mall.mbg.entity.OmsOrder;
import com.hgb.mall.mbg.entity.OmsOrderOperateHistory;
import com.hgb.mall.mbg.mapper.OmsOrderDynamicSqlSupport;
import com.hgb.mall.mbg.mapper.OmsOrderMapper;
import com.hgb.mall.mbg.mapper.OmsOrderOperateHistoryMapper;
import org.mybatis.dynamic.sql.SqlBuilder;
import org.mybatis.dynamic.sql.render.RenderingStrategies;
import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * 订单管理Service实现类
 * Created by hgb on 2020/10/11.
 */
@Service
public class OmsOrderServiceImpl implements OmsOrderService {
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OmsOrderDao orderDao;
    @Autowired
    private OmsOrderOperateHistoryDao orderOperateHistoryDao;
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;
    @Autowired
    private UmsAdminService adminService;

    @Override
    public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        return orderMapper.select(c -> c
                .where(OmsOrderDynamicSqlSupport.deleteStatus, isEqualTo(0))
                .and(OmsOrderDynamicSqlSupport.orderSn, isEqualToWhenPresent(queryParam.getOrderSn()))
                .and(OmsOrderDynamicSqlSupport.status, isEqualToWhenPresent(queryParam.getStatus()))
                .and(OmsOrderDynamicSqlSupport.sourceType, isEqualToWhenPresent(queryParam.getSourceType()))
                .and(OmsOrderDynamicSqlSupport.orderType, isEqualToWhenPresent(queryParam.getOrderType()))
                .and(OmsOrderDynamicSqlSupport.receiverName, isLikeWhenPresent(queryParam.getReceiverKeyword())
                                .then(s -> "%" + s + "%")
                        , or(OmsOrderDynamicSqlSupport.receiverPhone, isLikeWhenPresent(queryParam.getReceiverKeyword())
                                .then(s -> "%" + s + "%"))
                )
                .orderBy(OmsOrderDynamicSqlSupport.id.descending())
        );
    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderDao.delivery(deliveryParamList);
        //添加操作记录
        List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                                                                           .map(omsOrderDeliveryParam -> {
                                                                               OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                                                                               history.setOrderId(omsOrderDeliveryParam
                                                                                       .getOrderId());
                                                                               history.setCreateTime(new Date());
                                                                               history.setOperateMan("后台管理员");
                                                                               history.setOrderStatus(2);
                                                                               history.setNote("完成发货");
                                                                               return history;
                                                                           }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(operateHistoryList);
        return count;
    }

    @Override
    public int close(List<Long> ids, String note) {
        UpdateStatementProvider updateStatement = SqlBuilder.update(OmsOrderDynamicSqlSupport.omsOrder)
                                                            .set(OmsOrderDynamicSqlSupport.status).equalTo(4)
                                                            .where(OmsOrderDynamicSqlSupport.deleteStatus, isEqualTo(0))
                                                            .and(OmsOrderDynamicSqlSupport.id, isIn(ids))
                                                            .build()
                                                            .render(RenderingStrategies.MYBATIS3);
        int count = orderMapper.update(updateStatement);
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:" + note);
            return history;
        }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(historyList);
        return count;
    }

    @Override
    public int delete(List<Long> ids) {
        UpdateStatementProvider updateStatement = SqlBuilder.update(OmsOrderDynamicSqlSupport.omsOrder)
                                                            .set(OmsOrderDynamicSqlSupport.deleteStatus).equalTo(1)
                                                            .where(OmsOrderDynamicSqlSupport.deleteStatus, isEqualTo(0))
                                                            .and(OmsOrderDynamicSqlSupport.id, isIn(ids))
                                                            .build()
                                                            .render(RenderingStrategies.MYBATIS3);
        return orderMapper.update(updateStatement);
    }

    @Override
    public OmsOrderDetail detail(Long id) {
        return orderDao.getDetail(id);
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan(adminService.getCurrentAdmin().getUsername());
        history.setOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        insertOperateHistory(moneyInfoParam.getOrderId(), moneyInfoParam.getStatus(), "修改费用信息");
        return count;
    }

    private void insertOperateHistory(Long orderId, Integer status, String note) {
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setCreateTime(new Date());
        history.setOperateMan(adminService.getCurrentAdmin().getUsername());
        history.setOrderStatus(status);
        history.setNote(note);
        orderOperateHistoryMapper.insert(history);
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        order.setNote(note);
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        insertOperateHistory(id, status, "修改备注信息：" + note);
        return count;
    }
}
